﻿/*===注册类声明类型Start===*/
var Class = {
    create: function ()              // create Function  
    {
        return function () {
            this.initialize.apply(this, arguments);
        }
    }
};
/*===注册类声明类型End===*/

/*===定时任务实体Start===*/
var TimePlan = Class.create();
TimePlan.prototype = {
    //构造函数
    initialize: function (targetTime) {
        this.targetTime = targetTime;
        this.targetMilliSecond = (function (_targetTime) {
            var f = _targetTime.split(' ', 2);
            var d = (f[0] ? f[0] : '').split('-', 3);
            var t = (f[1] ? f[1] : '').split(':', 3);
            return (new Date(
            parseInt(d[0], 10) || null,
            (parseInt(d[1], 10) || 1) - 1,
            parseInt(d[2], 10) || null,
            parseInt(t[0], 10) || null,
            parseInt(t[1], 10) || null,
            parseInt(t[2], 10) || null
            )).getTime();
        }(this.targetTime));
        this.remainTime = { Day: 0, Hour: 0, Minute: 0, Second: 0 };
        window.TimePlanTemp = this;
    },
    //目标时间
    targetTime: "",
    //剩余时间
    remainTime: {},
    //要执行的任务
    work: function () { },
    //任务结束后事件
    completed: function () { },
    //间隔时间（默认1s）
    perTime: 1,
    //任务ID
    planID: null,
    //执行任务
    executePlan: function () {
        var self = window.TimePlanTemp;
        var startTime = self.targetMilliSecond;
        var currentTime = new Date();
        var result = (startTime - Date.parse(currentTime)) / 1000;
        if (result >= 0) {
            self.remainTime.Day = parseInt(result / 24 / 3600);
            self.remainTime.Hour = parseInt((result / 3600) % 24);
            self.remainTime.Minute = parseInt((result / 60) % 60);
            self.remainTime.Second = parseInt(result % 60);
            $plan = self.executePlan;
            if (!self.planID) {
                self.planID = setInterval(function () { $plan(); }, self.perTime * 1000);
            }
            self.work();
        }
        else {
            if (self.planID) {
                clearInterval(self.planID);
                self.completed();
            }
            delete window.TimePlanTemp;
        }
    }
};
/*===定时任务实体End===*/